package com.xiaolei.openokjoke.Activitys

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Message
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.util.Base64
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.widget.RadioButton
import com.umeng.analytics.MobclickAgent
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.xiaolei.easyfreamwork.base.FragmentPagerAdapter
import com.xiaolei.openokjoke.ActivityStore
import com.xiaolei.openokjoke.Base.BaseV4Activity
import com.xiaolei.openokjoke.Beans.ShareMsgBean
import com.xiaolei.openokjoke.Configs.EventAction
import com.xiaolei.openokjoke.Exts.enqueue
import com.xiaolei.openokjoke.Fragments.*
import com.xiaolei.openokjoke.Net.APPNet
import com.xiaolei.openokjoke.Net.BaseRetrofit
import com.xiaolei.openokjoke.R
import com.xiaolei.openokjoke.UM.UMShare
import com.xiaolei.openokjoke.Utils.PermisstionUtil
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*


/**
 * 主界面
 */
class MainActivity : BaseV4Activity()
{
    private val share by lazy {
        UMShare(this)
    }
    private val fragments by lazy {
        LinkedList<Fragment>().apply {
            add(RandomFragment())
            add(TxtJokeFragment())
            add(JpgJokeFragment())
            add(GifJokeFragment())
        }
    }
    private val radioArray by lazy { arrayOf(suiji, txt, jpg, gif) }
    private val adapter by lazy {
        FragmentPagerAdapter(supportFragmentManager, fragments)
    }

    private val appNet by lazy {
        BaseRetrofit.create(APPNet::class.java)
    }
    private val channel by lazy {
        try
        {
            val appInfo = this.packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
            appInfo.metaData.getString("UMENG_CHANNEL")
        } catch (e: PackageManager.NameNotFoundException)
        {
            ""
        }
    }
    private lateinit var shareMsgBean: ShareMsgBean

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun initObj()
    {

    }

    override fun initView()
    {
        
    }

    override fun initData()
    {
        val call = appNet.sharemsg(channel)
        call.enqueue(this, { result ->
            result.content?.let {
                if (!::shareMsgBean.isInitialized)
                {
                    shareMsgBean = it
                }
            }
        }, {}, {})
    }

    override fun setListener()
    {
        val clickListener = View.OnClickListener {
            val position = radioArray.indexOf(it)
            if (viewpager.currentItem == position)
            {
                // 这里点击相同，需要刷新当前界面
                post(Message.obtain().apply {
                    what = when (position)
                    {
                        0 -> EventAction.refreshSuiji
                        1 -> EventAction.refreshTxt
                        2 -> EventAction.refreshJpg
                        3 -> EventAction.refreshGif
                        else -> -1
                    }
                })

            } else
            {
                clickRadioButton(position)
                viewpager.currentItem = position
                app_title.setTitleText((it as RadioButton).text)
            }
        }
        suiji.isChecked = true
        suiji.setOnClickListener(clickListener)
        txt.setOnClickListener(clickListener)
        jpg.setOnClickListener(clickListener)
        gif.setOnClickListener(clickListener)

        // viewPager的切换事件
        viewpager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener()
        {
            override fun onPageSelected(position: Int)
            {
                clickRadioButton(position)
                val radioButton = radioArray[position]
                app_title.setTitleText(radioButton.text)
            }
        })
        // 点击菜单按钮
        app_title.setOnLeftImageClick {
            drawer_layout.openDrawer(Gravity.START)
        }
        app_title.setOnRightImageClick {
            if (::shareMsgBean.isInitialized) // 如果已经初始化，直接分享出去
            {
                val web = UMWeb(shareMsgBean.link)
                web.title = shareMsgBean.title //标题
                web.setThumb(UMImage(this, shareMsgBean.icon))  //缩略图
                web.description = shareMsgBean.subject //描述
                share.shareURL(web).open()
            } else // 否则再去网上获取一次
            {
                Toast("正在获取,请稍后..")
                val call = appNet.sharemsg(channel)
                call.enqueue(this, { result ->
                    result.content?.let {
                        if (!::shareMsgBean.isInitialized)
                        {
                            shareMsgBean = it
                        }
                        val web = UMWeb(shareMsgBean.link)
                        web.title = shareMsgBean.title //标题
                        web.setThumb(UMImage(this, shareMsgBean.icon))  //缩略图
                        web.description = shareMsgBean.subject //描述
                        share.shareURL(web).open()
                    }
                }, {})
            }
        }
    }

    /**
     * 点击哪个按钮
     */
    private fun clickRadioButton(position: Int)
    {
        radioArray.forEach {
            it.isChecked = position == radioArray.indexOf(it)
        }
    }

    override fun loadData()
    {
        PermisstionUtil.checkPermisstion(this, arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE))
        viewpager.adapter = adapter
    }

    private var clickTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if (System.currentTimeMillis() - clickTime <= 2 * 1000)
            {
                MobclickAgent.onKillProcess(this)
                ActivityStore.finishAll()
                ActivityStore.exit()
            } else
            {
                Toast("再按一次退出程序")
                clickTime = System.currentTimeMillis()
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onEvent(msg: Message)
    {
        if (msg.what == EventAction.closeDrawer)
        {
            drawer_layout.closeDrawer(Gravity.START, false)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
    {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

}
